﻿using System;
using System.Linq;
using System.Web;
using SailHero.Soft.FrameWork.DAO.Common;
using SailHero.Soft.FrameWork.DAO.Contracts.Contracts;
namespace SailHero.Soft.FrameWork.DAO.Core
{
    public class DAOInit : IDAOInit
    {

        #region fileds
        private string mpdll = "";
        private string DbAndConnStrNanme = "";
        private string NameSpace = "";
        #endregion

        public void InitDbContext_Win()
        {

            try
            {
                DbContextManager.InitStorage(new SimpleDbContextStorage());
                var config = DAOConfigurationSection.GetInstance();
                string basePath = AppDomain.CurrentDomain.BaseDirectory;
                if (config != null && config.MapingConfigs != null)
                {
                    config.MapingConfigs.Cast<DAOConfigurationElement>().ForEach(c =>
                    {
                        if (!string.IsNullOrEmpty(c.ConnStrName) && !string.IsNullOrEmpty(c.type))
                        {
                            DbAndConnStrNanme = c.ConnStrName;
                            string DBMapType = c.type;
                            mpdll = basePath + @"/" + DBMapType.Split(',')[1] + ".dll";
                            NameSpace = DBMapType.Split(',')[0];
                            // 初始化数据库
                            DbContextManager.InitDbContext(DbAndConnStrNanme, mpdll, NameSpace);
                        }
                    });
                }
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        public void InitDbContext_Web(HttpApplication app)
        {

            try
            {
                // 初始化数据库
                DbContextManager.InitStorage(new WebDbContextStorage(app));
                var config = DAOConfigurationSection.GetInstance();
                string basePath = AppDomain.CurrentDomain.BaseDirectory;
                if (config != null && config.MapingConfigs != null)
                {
                    config.MapingConfigs.Cast<DAOConfigurationElement>().ForEach(c =>
                    {
                        if (!string.IsNullOrEmpty(c.ConnStrName) && !string.IsNullOrEmpty(c.type))
                        {
                            DbAndConnStrNanme = c.ConnStrName;
                            string DBMapType = c.type;
                            mpdll = basePath + @"/bin/" + DBMapType.Split(',')[1] + ".dll";
                            NameSpace = DBMapType.Split(',')[0];
                            // 初始化数据库
                            DbContextManager.InitDbContext(DbAndConnStrNanme, mpdll, NameSpace);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                throw;
            }


        }
    }
}
